# mqtt/mqtt_client.py
import paho.mqtt.client as mqtt
from django.conf import settings
import time

class MqttPublisher:
    """MQTT 消息发送工具类"""
    def __init__(self):
        # 从 settings 读取配置
        self.broker = getattr(settings, "MQTT_BROKER", "127.0.0.1")
        self.port = getattr(settings, "MQTT_PORT", 1883)
        self.username = getattr(settings, "MQTT_USERNAME", "")
        self.password = getattr(settings, "MQTT_PASSWORD", "")
        self.client = mqtt.Client()

        # 设置认证
        if self.username and self.password:
            self.client.username_pw_set(self.username, self.password)

    def connect(self):
        """连接 MQTT 服务器"""
        try:
            self.client.connect(self.broker, self.port, keepalive=60)
            self.client.loop_start()
            print("连接成功")
            return True
        except Exception as e:
            print(f"连接 MQTT 服务器失败: {e}")
            return False

    def publish(self, topic, message):
        """发送消息到指定主题"""
        print(self.client,self.client.is_connected())
        if not self.client.is_connected():
            print("重连接")
            # 若未连接，尝试重连
            if not self.connect():
                return False

        try:
            # 发送消息（QoS=0，不保留消息）
            result = self.client.publish(topic, message, qos=0, retain=False)
            # 等待消息发送完成
            result.wait_for_publish()
            return True
        except Exception as e:
            print(f"发送消息失败: {e}")
            return False

    def disconnect(self):
        """断开连接"""
        self.client.disconnect()